package gzhaoku.com.common.util;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.widget.Toast;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import gzhaoku.com.common.Logger;

/**
 * APK安装工具
 */
public class ApkInstaller {

    static final Logger log = Logger.getLog(ApkInstaller.class);




    /**
     * 静默安装
     * @param filePath
     * @return
     */
    public static int install(final Activity context,String filePath){
        log.i("Install apk:"+filePath);
        File file = new File(filePath);
        if(!file.exists()){
            return -1;
        }

        if(!file.isFile()){
            return -2;
        }

//        String[] args = {"pm" , "install", "-r", filePath};
//
//        ProcessBuilder processBuilder = new ProcessBuilder(args);
//
//        Process process = null;
//
//        BufferedReader sucessResult = null;
//        BufferedReader errorResult = null;
//        StringBuilder successMsg = new StringBuilder();
//        StringBuilder errorMsg = new StringBuilder();
//
//        int result;
//
//        try{
//            process = processBuilder.start();
//            sucessResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
//            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
//            String s;
//            while((s=sucessResult.readLine()) != null){
//                successMsg.append(s);
//            }
//
//            while((s=errorResult.readLine()) != null){
//                errorMsg.append(s);
//            }
//        }catch (Exception e){
//            log.e(e);
//        }finally {
//            IOUtils.close(sucessResult, errorResult);
//            if(process != null){
//                process.destroy();
//            }
//        }
//
//
//
//        if(StringUtils.containsIgnoreCase(successMsg.toString(), "success")){
//            return 0;
//        }else{
//
////            toast(context, "Failed pm install:"+successMsg.toString());
//
//            Intent install = new Intent(Intent.ACTION_VIEW);
//            install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
//            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.startActivity(install);
//
//
//            return -3;
//        }


        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            Uri contentUri = FileProvider.getUriForFile(context, "gzhaoku.com.machinemain.Boot", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }else{
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");

        }

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        return 0;
    }

    private static void toast(final Activity context, final String msg){
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
            }
        });
    }
}
